package com.dailyblue.project.smbms.alibaba.alipay.controller;

import com.alibaba.fastjson.JSONArray;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.dailyblue.project.smbms.alibaba.alipay.feign.AlipayFeign;
import com.dailyblue.project.smbms.alibaba.commons.bean.AlipayBean;
import com.dailyblue.project.smbms.alibaba.commons.util.JsonResult;
import com.dailyblue.project.smbms.alibaba.commons.util.ResultTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/alipay")
@Slf4j
@CrossOrigin
public class AlipayController {
    @Resource
    private RocketMQTemplate rocketMQTemplate;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Value("${appId}")
    private String appId;
    @Value("${privateKey}")
    private String privateKey;
    @Value("${publicKey}")
    private String publicKey;
    @Value("${notifyUrl}")
    private String notifyUrl;
    @Value("${returnUrl}")
    private String returnUrl;
    @Value("${signType}")
    private String signType;
    @Value("${charset}")
    private String charset;
    @Value("${gatewayUrl}")
    private String gatewayUrl;
    @Resource
    private AlipayFeign alipayFeign;

    // 前端必须通过跳转方式调用这个方法
    @RequestMapping("/pay")
    public String pay(AlipayBean alipayBean, int aid, String order, HttpSession session) throws AlipayApiException {
        String orderId = new Date().getTime() + "." + (int) (Math.random() * 1000);
        alipayBean.setOut_trade_no(orderId);
        log.info("alipayBean:{},aid:{},order:{}", alipayBean, aid, order);
        session.setAttribute("ALIPAYBEAN", alipayBean);
        session.setAttribute("AID", aid);
        session.setAttribute("ORDER", order);
        // 产生Alipay客户端
        AlipayClient alipayClient
                = new DefaultAlipayClient(gatewayUrl, appId, privateKey, "json", charset, publicKey, signType);
        // 调用支付宝接口
        AlipayTradePagePayRequest alipayTradeAppPayRequest = new AlipayTradePagePayRequest();
        // 设置付款成功后应跳转的路径
        alipayTradeAppPayRequest.setNotifyUrl("http://localhost:8029/alipay/success");
        alipayTradeAppPayRequest.setReturnUrl("http://localhost:8029/alipay/success");
        // 设置支付宝的各项参数
        String json = JSONArray.toJSONString(alipayBean);
        alipayTradeAppPayRequest.setBizContent(json);
        // 生成最终的订单
        String result = alipayClient.pageExecute(alipayTradeAppPayRequest).getBody();
        log.info("{}", result);
        return result;
    }

    @RequestMapping("/success")
    public String success(HttpSession session) {
        AlipayBean alipayBean = (AlipayBean) session.getAttribute("ALIPAYBEAN");
        // 负责将消息生产到rocketMQ
        Map<String, String> map = new HashMap<>();
        map.put("orderId", alipayBean.getOut_trade_no());
        String aid = session.getAttribute("AID").toString();
        map.put("aid", aid);
        String order = session.getAttribute("ORDER").toString();
        map.put("order", order);
        SendResult sendResult = rocketMQTemplate.syncSend("Alipay:tag", JSONArray.toJSON(map));
        log.info("返回结果是:{}", sendResult);
        // 以下四个是消费者
        // 生成订单记录  aid orderId gid num  👌
        // 清空购物车
        String uid = alipayFeign.find(aid).getData().toString();
        stringRedisTemplate.delete("USER:" + uid);
        // 库存数量相减   👌
        // 生成一笔物流记录👌
        return "支付成功";
    }
}
